package frame

import "strings"

/*
权限代号命名规则
user=用户
user.create=用户创建

2=用户
2.2=用户创建
*/
type permissionDomain struct {
	server         *Server
	permissionsMap map[string]*Permission
	permissions    []*Permission
}

// 权限输出
type Permission struct {
	Name   string        `json:"name"`
	Id     string        `json:"id"`
	Childs []*Permission `json:"childs"`
	Pid    string        `json:"pid"`
}

func (this *permissionDomain) add(name string, codes ...string) {
	if len(codes) != 1 {
		return
	}
	var code = codes[0]
	if this.permissionsMap == nil {
		this.permissionsMap = make(map[string]*Permission)
	}
	if _, ok := this.permissionsMap[code]; ok {
		return
	}
	p := &Permission{Name: name, Id: code}
	codeArr := strings.Split(code, ".")
	if len(codeArr) > 1 {
		p.Pid = strings.Join(codeArr[:len(codeArr)-1], ".")
	}
	this.permissionsMap[code] = p
	this.permissions = append(this.permissions, p)
}

func (this *permissionDomain) _getPermissions(parentCode string, list []*Permission) []*Permission {
	plist := make([]*Permission, 0)
	for index, item := range this.permissions {
		if item.Pid == parentCode {
			item.Childs = this._getPermissions(item.Id, this.permissions[index+1:])
			plist = append(plist, item)
		}
	}
	return plist
}

// 获取所有权限结构树
func (this *permissionDomain) getPermissions() []*Permission {
	return this._getPermissions("", this.permissions)
}
